import React, { useRef } from "react";
import _ from 'lodash'
import { Form, Input, Select, Space, Button, DatePicker, Tabs } from "antd";
import { SearchOutlined, ExclamationCircleFilled } from "@ant-design/icons";
import { getDateTime3 } from '@/utils/getDate'
import { apiServicePage, apiServiceApprove, apiServiceRejected } from '@/request/services'
import ThePagination from "@/components/ThePagination";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import TheDialog from "@/components/TheDialog";
import TheImage from '@/components/TheImage'
import Detail from "../component/Detail";
import "@/views/commodity/style/style.less";

const { RangePicker } = DatePicker;
const { TabPane } = Tabs;
const { TextArea } = Input;

const SearchHeader = ({ getValue }) => {
  const formRef = useRef()
  const onFinish = (values) => {
    if (values.time && values.time.length) {
      values.serviceStartDate = getDateTime3(values.time[0])
      values.serviceEndDate = getDateTime3(values.time[1])
    }
    delete (values.time)
    _.forIn(values, (v, k) => {
      if (!v) {
        delete (values[k])
      }
    })
    getValue(values)
  }
  const reset = () => {
    formRef.current.setFieldsValue({
      storeServiceName: '',
      serviceId: '',
      serviceStatus: '',
      time: []
    })
    getValue({})
  };
  return (
    <Form layout={'inline'} ref={formRef} onFinish={onFinish}>
      <Form.Item name={"storeServiceName"}>
        <Input style={{ width: 140 }} suffix={<SearchOutlined />} placeholder={"服务名称"} />
      </Form.Item>
      <Form.Item name={"serviceId"}>
        <Input style={{ width: 140 }} suffix={<SearchOutlined />} placeholder={"服务ID"} />
      </Form.Item>
      {/* <Form.Item name={"serviceStatus"} label="上架状态">
        <Select
          style={{ width: 140 }}
          options={[{ value: 'Y', label: '上架' }, { value: 'N', label: '下架' }, { value: 'G', label: '管理员关闭' }]}
          placeholder={"上架状态"}
        />
      </Form.Item> */}
      <Form.Item name={"time"} label="申请时间">
        <RangePicker />
      </Form.Item>
      <Form.Item>
        <Space size="small" style={{ marginLeft: 10 }}>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
          <Button onClick={reset}>重置</Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

class Examine extends React.Component {
  state = {
    columnsS: [
      {
        title: "服务ID",
        dataIndex: "serviceId",
        key: "serviceId",
      },
      {
        title: "服务名称",
        dataIndex: "serviceName",
        key: "serviceName",
      },
      {
        title: "服务logo",
        dataIndex: "serviceShowFile",
        key: "serviceShowFile",
        render: (text, render) => {
          return <TheImage src={render.serviceShowFile} width={80} height={80} />
        }
      },
      {
        title: "服务分类",
        dataIndex: "serviceClassifyName",
        key: "serviceClassifyName",
      },
      {
        title: "服务价格",
        dataIndex: "serviceRealPrice",
        key: "serviceRealPrice",
        render: (text, render) => {
          return <React.$Price price={render.serviceRealPrice || 0} />
        }
      },
      {
        title: "预约时间",
        render: (text, render) => {
          return <div>
            {render.serviceStartTime} 至 {render.serviceEndTime}
          </div>
        }
      },
      {
        title: "所属商家",
        dataIndex: "storeName",
        key: "storeName",
      },
      {
        title: "审核状态",
        render: () => {
          return '待审核'
        }
      },
      {
        title: "申请时间",
        dataIndex: "updateTime",
        key: "updateTime",
      },
      {
        title: "操作",
        fixed: "right",
        render: (text, render) => {
          return (
            <div>
              <TheButton haspermi={['service:details']} onClick={() => this.setState({ detailVisible: true, serviceId: render.serviceId })}>查看详情</TheButton>
              <TheButton haspermi={['service:pass']} onClick={() => this.cancelConfirm(render.serviceId)}>通过</TheButton>
              <TheButton haspermi={['service:rejected']} onClick={() => this.setState({ visible: true, serviceIdB: render.serviceId,textArea:'' })}>
                驳回
              </TheButton>
            </div>
          );
        },
      },
    ],
    dataS: [],
    columnsB: [
      {
        title: "服务ID",
        dataIndex: "serviceId",
        key: "serviceId",
      },
      {
        title: "服务名称",
        dataIndex: "serviceName",
        key: "serviceName",
      },
      {
        title: "服务logo",
        dataIndex: "serviceShowFile",
        key: "serviceShowFile",
        render: (text, render) => {
          return <TheImage src={render.serviceShowFile} width={80} height={80} />
        }
      },
      {
        title: "服务分类",
        dataIndex: "serviceClassifyName",
        key: "serviceClassifyName",
      },
      {
        title: "服务价格",
        dataIndex: "serviceRealPrice",
        key: "serviceRealPrice",
        render: (text, render) => {
          return <React.$Price price={render.serviceRealPrice || 0} />
        }
      },
      {
        title: "预约时间",
        render: (text, render) => {
          return <div>
            {render.serviceStartTime} 至 {render.serviceEndTime}
          </div>
        }
      },
      {
        title: "所属商家",
        dataIndex: "storeName",
        key: "storeName",
      },
      {
        title: "审核状态",
        render: () => {
          return "未通过"
        }
      },
      {
        title: "申请时间",
        dataIndex: "updateTime",
        key: "updateTime",
      },
      {
        title: "原因",
        dataIndex: "refuseReason",
        key: "refuseReason",
        render: (text, record) => {
          return <div className="p-white-space" style={{ width: 200 }}>{record.refuseReason}</div>
        }
      },
    ],
    dataB: [],
    pageDataS: {
      pageNo: 1,
      pageSize: 10,
    },
    totalS: 0,
    pageDataB: {
      pageNo: 1,
      pageSize: 10,
    },
    totalB: 0,
    visible: false,
    approvalStatus: 'S',
    searchValue: {},
    serviceId: '',
    detailVisible: false,
    serviceIdB: '',
    textArea: ''
  };
  async componentDidMount() {
    await this.getData()
  }
  getData = async () => {
    const { approvalStatus, searchValue } = this.state
    let res = await apiServicePage({ approvalStatus, ...searchValue, ...this.state[`pageData${approvalStatus}`] })
    if (res.data && res.code === 0) {
      this.setState({
        [`data${approvalStatus}`]: res.data,
        [`pageData${approvalStatus}`]: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        [`total${approvalStatus}`]: res.totalCount
      })
    }
  }
  tabChange = (key) => {
    this.setState({
      approvalStatus: key
    }, () => {
      this.getData()
    })
  };
  pageChangeS = (pageNo, pageSize) => {
    this.setState({
      pageDataS: {
        pageNo, pageSize
      }
    }, () => this.getData())
  };
  pageChangeB = (pageNo, pageSize) => {
    this.setState({
      pageDataB: {
        pageNo, pageSize
      }
    }, () => this.getData())
  };
  getValue = (value) => {
    this.setState({
      searchValue: value,
      pageDataS: {
        pageNo: 1,
        pageSize: 10
      },
      pageChangeB: {
        pageNo: 1,
        pageSize: 10
      }
    }, () => {
      this.getData()
    })
  }
  cancelConfirm = (serviceId) => {
    React.$confirm({
      title: "您确认通过审核本条商品吗？",
      onOk: async () => {
        await apiServiceApprove({ serviceId })
        this.getData()
      },
    });
  };
  handleCancel = () => {
    this.setState({ visible: false });
  };
  handleOk = async () => {
    let dismissReason = this.state.textArea
    if (!dismissReason || !dismissReason.length) {
      return React.$message({
        type: 'error',
        content: '驳回原因为必填项！'
      })
    }
    let { serviceIdB } = this.state
    await apiServiceRejected({ serviceId: serviceIdB, dismissReason })
    this.setState({ visible: false, serviceIdB: '',textArea:'' }, () => {
      this.getData()
    });
  };
  detailClose = () => {
    this.setState({
      detailVisible: false,
      serviceId: '',
      serviceIdB: ''
    })
  }
  render() {
    const {
      columnsS,
      columnsB,
      dataS,
      dataB,
      pageDataS,
      pageDataB,
      totalS,
      totalB,
      visible,
      detailVisible,
      serviceId
    } = this.state;
    return (
      <div className="p-layout-box commodity-examine">
        <div className="p-search-box">
          <SearchHeader getValue={this.getValue} />
        </div>
        <Tabs defaultActiveKey="S" onChange={this.tabChange}>
          <TabPane tab="待审核" key="S">
            <div className="p-layout-content-pagination">
              <TheTable
                scroll={{ x: "max-content", y: '63vh' }}
                columns={columnsS}
                dataSource={dataS}
              />
              <ThePagination
                pageNo={pageDataS.pageNo}
                pageSize={pageDataS.pageSize}
                total={totalS}
                pageChange={this.pageChangeS}
              />
            </div>
          </TabPane>
          <TabPane tab="未通过" key="B">
            <div className="p-layout-content-pagination">
              <TheTable
                scroll={{ x: "max-content", y: '63vh' }}
                columns={columnsB}
                dataSource={dataB}
              />
              <ThePagination
                pageNo={pageDataB.pageNo}
                pageSize={pageDataB.pageSize}
                total={totalB}
                pageChange={this.pageChangeB}
              />
            </div>
          </TabPane>
        </Tabs>
        <TheDialog
          title="服务详情"
          visible={detailVisible}
          handleCancel={this.detailClose}
          footer={null}
        >
          <Detail serviceId={serviceId} />
        </TheDialog>
        <TheDialog
          title={
            <div>
              <ExclamationCircleFilled
                style={{ color: "#FAAD14", marginRight: 10 }}
              />
              输入驳回原因
            </div>
          }
          width={400}
          visible={visible}
          handleCancel={this.handleCancel}
          handleOk={this.handleOk}
        >
          <TextArea
            onChange={(e) => this.setState({
              textArea: e.target.value
            })}
            allowClear
            autoSize={{ minRows: 6, maxRows: 6 }}
            maxLength={140}
            showCount
          />
        </TheDialog>
      </div>
    );
  }
}

export default Examine;
